<?php
/**
 * lps.php
 *
 * @package live product search
 * @copyright Copyright 2007-2008 Numinix Technology http://www.numinix.com
 * @copyright Portions Copyright 2003-2006 Zen Cart Development Team
 * @copyright Portions Copyright 2003 osCommerce
 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
 * @version $Id: lps.php 8 2008-09-21 04:02:13Z numinix $
 */
@define('LPS_VERSION', '$Revision: 9 $ $Date: 2010-03-27 $ $Author: philip_clarke $');
/*
Live Product Search - Attribute List - http://help.live.com/help.aspx?project=wl_agora&market=en-us&querytype=keyword&query=2ofnitamrofelif&tmt=msnMain&domain=productupload.live.com&format=b1
*/
	require('includes/application_top.php');
  require(DIR_WS_CLASSES . 'lps.php');
  $lps = new lps();

	@define('LPS_EXPIRATION_DAYS', 30);
	@define('LPS_EXPIRATION_BASE', 'now'); // now/product
	@define('LPS_OFFER_ID', 'id'); // id/model/false
	@define('LPS_DIRECTORY', 'feed/');
	@define('LPS_OUTPUT_BUFFER_MAXSIZE', 1024*1024);
	@define('LPS_CHECK_IMAGE', 'false');
	@define('LPS_STAT', false);
	$anti_timeout_counter = 0; //for timeout issues as well as counting number of products processed
	$lps_products_counter = 0; //counts all products regardless of inclusion
	$max_limit = false;
	@define('LPS_USE_CPATH', 'false');
	@define('NL', "<br />\n");
	@define('LPS_LANGUAGE_DISPLAY', true);
	@define('LPS_CURRENCY_DISPLAY', true);
	$outfile = DIR_FS_CATALOG . LPS_DIRECTORY . LPS_OUTPUT_FILENAME;
	//BEGIN MAGIC SEO URLS
	if (LPS_MAGIC_SEO_URLS == 'true') {
		require_once(DIR_WS_CLASSES . 'msu_ao.php');
	 	include(DIR_WS_INCLUDES . 'modules/msu_ao_1.php');
 	}
 	//END MAGIC SEO URLS

  // process parameters
  $parameters = explode('_', $_GET['feed']); // ?feed=fy_uy
  $feed_parameter = $parameters[0];
  $feed = $lps->get_feed($feed_parameter);
  $upload_parameter = $parameters[1];
  $upload = $lps->get_upload($upload_parameter);


	require(zen_get_file_directory(DIR_WS_LANGUAGES . $_SESSION['language'] .'/', 'lps.php', 'false'));

	$languages = $db->execute("select code, languages_id from " . TABLE_LANGUAGES . " where name='" . "English" . "' limit 1");

	$product_url_add = (LPS_LANGUAGE_DISPLAY == 'true' ? "&language=" . $languages->fields['code'] : '') . (LPS_CURRENCY_DISPLAY == 'true' ? "&currency=" . LPS_CURRENCY : ''); // true

	echo TEXT_LPS_STARTED . NL;
	echo TEXT_LPS_FILE_LOCATION . $outfile . NL;
	echo "Processing: Feed - " . (isset($feed) && $feed == "yes" ? "Yes" : "No") . ", Upload - " . (isset($upload) && $upload == "yes" ? "Yes" : "No") . NL;

if (isset($feed) && $feed == "yes") {
	if (is_dir(DIR_FS_CATALOG . LPS_DIRECTORY)) {
	  $fc->unlock(DIR_FS_CATALOG . LPS_DIRECTORY);
		if (!is_writeable(DIR_FS_CATALOG . LPS_DIRECTORY)) {
			echo ERROR_LPS_DIRECTORY_NOT_WRITEABLE . NL;
			die;
		}
	} else {
		echo ERROR_LPS_DIRECTORY_DOES_NOT_EXIST . NL;
		die;
	}

	$stimer_feed = $lps->microtime_float();
	if (!get_cfg_var('safe_mode') && function_exists('safe_mode')) {
		set_time_limit(0);
	}

	$output_buffer = "";

	/*if(!$lps->lps_fwrite()) {
		echo ERROR_LPS_OPEN_FILE . NL;
		die;
	}*/

	if (file_exists($outfile)) {
		$fc->unlock($outfile);
	} else {
		$fc->unlock(dirname($outfile));
		fopen($outfile, "w");
	}

	if (is_writeable($outfile)) {

		$content = array();

		$content["xml_start"] = '<DataFeed xmlns="urn:merchant-schema">';
		$content["collection_start"] = '<OfferCollection>';
		$lps->lps_fwrite($content, "wb");


		$categories_array = $lps->lps_category_tree();

		if (LPS_UPC == 'true' || LPS_ISBN == 'true') {
		$products_query = "SELECT distinct(p.products_id), p.products_model, pd.products_name, pd.products_description, p.products_image, p.products_tax_class_id, p.products_price_sorter, p.products_upc, p.products_isbn, s.specials_new_products_price, s.expires_date, GREATEST(p.products_date_added, IFNULL(p.products_last_modified, 0), IFNULL(p.products_date_available, 0)) AS base_date, m.manufacturers_name, p.products_quantity, pt.type_handler
										 FROM " . TABLE_PRODUCTS . " p
											 LEFT JOIN " . TABLE_MANUFACTURERS . " m ON (p.manufacturers_id = m.manufacturers_id)
											 LEFT JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd ON (p.products_id = pd.products_id)
											 LEFT JOIN " . TABLE_PRODUCT_TYPES . " pt ON (p.products_type=pt.type_id)
											 LEFT JOIN " . TABLE_SPECIALS . " s ON (s.products_id = p.products_id)
										 WHERE p.products_status = 1
											 AND p.product_is_call <> 1
											 AND p.product_is_free <> 1
											 AND pd.language_id = " . (int)$languages->fields['languages_id'] . "
                     GROUP BY p.products_id
										 ORDER BY p.products_id ASC";
		} else {
		$products_query = "SELECT distinct(p.products_id), p.products_model, pd.products_name, pd.products_description, p.products_image, p.products_tax_class_id, p.products_price_sorter, s.specials_new_products_price, s.expires_date, GREATEST(p.products_date_added, IFNULL(p.products_last_modified, 0), IFNULL(p.products_date_available, 0)) AS base_date, m.manufacturers_name, p.products_quantity, pt.type_handler
										 FROM " . TABLE_PRODUCTS . " p
											 LEFT JOIN " . TABLE_MANUFACTURERS . " m ON (p.manufacturers_id = m.manufacturers_id)
											 LEFT JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd ON (p.products_id = pd.products_id)
											 LEFT JOIN " . TABLE_PRODUCT_TYPES . " pt ON (p.products_type=pt.type_id)
											 LEFT JOIN " . TABLE_SPECIALS . " s ON (s.products_id = p.products_id)
										 WHERE p.products_status = 1
											 AND p.product_is_call <> 1
											 AND p.product_is_free <> 1
											 AND pd.language_id = " . (int)$languages->fields['languages_id'] . "
                     GROUP BY p.products_id
										 ORDER BY p.products_id ASC";
		}

		$products = $db->Execute($products_query);
		$tax_rate = array();
		$starting_point = LPS_START_PRODUCTS;
			while (!$products->EOF && !$max_limit) { // run until end of file or until maximum number of products reached
				$lps_products_counter++;
				list($categories_list, $cPath) = $lps->lps_get_category($products->fields['products_id']);
				if ($lps->numinix_categories_check(LPS_POS_CATEGORIES, $products->fields['products_id'], 1) == true && $lps->numinix_categories_check(LPS_NEG_CATEGORIES, $products->fields['products_id'], 2) == false && ($lps_products_counter >= $starting_point)) { // check to see if category limits are set.  If so, only process for those categories.
					$price = zen_get_products_actual_price($products->fields['products_id']);
					if ($price > 0) {
						$anti_timeout_counter++;
						if ($anti_timeout_counter == LPS_MAX_PRODUCTS && LPS_MAX_PRODUCTS != 0) { // if counter is greater than or equal to maximum products
							$max_limit = true; // then max products reached
						} else {
							$max_limit = false; // otherwise, max products not reached
						}
						if (!isset($tax_rate[$products->fields['products_tax_class_id']])) {
							$tax_rate[$products->fields['products_tax_class_id']] = zen_get_tax_rate($products->fields['products_tax_class_id']);
						}
						$price = zen_add_tax($price, $tax_rate[$products->fields['products_tax_class_id']]);
						$price = $currencies->value($price, true, LPS_CURRENCY, $currencies->get_value(LPS_CURRENCY));
						if (LPS_MAGIC_SEO_URLS == 'true') {
							include(DIR_WS_INCLUDES . 'modules/msu_ao_2.php');
						} else {
							$link = ($products->fields['type_handler'] ? $products->fields['type_handler'] : 'product') . '_info';
							$cPath_href = (LPS_USE_CPATH == 'true' ? 'cPath=' . $cPath . '&' : '');
							$link = zen_href_link($link, $cPath_href . 'products_id=' . (int)$products->fields['products_id'] . $product_url_add, 'NONSSL', false);
						}
						$content = array();
						$content["item_start"] = "\n" . '<Offer>';
						$content["title"] = '<OfferName>' . $lps->lps_xml_sanitizer($products->fields['products_name'], true) . '</OfferName>';

						$content["brand"] = '<Brand>' . $lps->lps_xml_sanitizer($products->fields['manufacturers_name'], true) . '</Brand>';

						$product_type = $lps->lps_get_category($products->fields['products_id']);
						array_pop($product_type); // removes category number from end
						$product_type = explode(',', $product_type[0]);
						if (LPS_PRODUCT_TYPE == 'top') {
							$top_level = array_shift($product_type);
							$top_level = htmlentities($top_level);
							$content["product_type"] = '<MerchantCategory>' . $lps->lps_xml_sanitizer($top_level, true) . '</MerchantCategory>';
						} elseif (LPS_PRODUCT_TYPE == 'bottom') {
							$bottom_level = array_pop($product_type); // sets last category in array as bottom-level
							$bottom_level = htmlentities($bottom_level);
							$content["product_type"] = '<MerchantCategory>' . $lps->lps_xml_sanitizer($bottom_level, true) . '</MerchantCategory>';
						} else {
							$full_path = implode("|", $product_type);
							$full_path = htmlentities($full_path);
							$content["product_type"] = '<MerchantCategory>' . $lps->lps_xml_sanitizer($full_path, true) . '</MerchantCategory>';
						}

						if ($lps->lps_image_url($products->fields['products_image']) != '') {
							$content["image_link"] = '<ReferenceImageURL>' . $lps->lps_image_url($lps->lps_xml_sanitizer($products->fields['products_image'])) . '</ReferenceImageURL>';
						}
						$content["link"] = '<ActionURL>' . $link . '</ActionURL>';
						$content["price"] = '<RegularPrice>' . number_format($price, 2, '.', '') . '</RegularPrice>';
						if (LPS_UPC == 'true') {
							$content["upc"] = '<UPC>' . $lps->lps_sanita($products->fields['products_upc'], true) . '</UPC>';
						}
						if (LPS_ISBN == 'true') {
							$content["isbn"] = '<ISBN>' . $lps->lps_sanita($products->fields['products_isbn'], true) . '</ISBN>';
						}
						$content["description"] = '<OfferDescription>' . $lps->lps_xml_sanitizer($lps->ShortenText($products->fields['products_description'], 1000), true) . '</OfferDescription>';
						$content["item_end"] = '</Offer>';
						$lps->lps_fwrite($content, "a");
					}
				}
				$products->MoveNext();
			}
			$content = array();
			$content["collection_end"] = '</OfferCollection>';
			$content["xml_end"] = '</DataFeed> ';
			$lps->lps_fwrite($content, "a");
			chmod($outfile, 0655);
			$fc->relock($outfile);
			$fc->relock(dirname($outfile));
		} else {
			echo ERROR_LPS_OPEN_FILE . NL;
			die;
		}



	$timer_feed = $lps->microtime_float()-$stimer_feed;

	echo TEXT_LPS_FEED_COMPLETE . ' ' . LPS_TIME_TAKEN . ' ' . sprintf("%f " . TEXT_LPS_FEED_SECONDS, number_format($timer_feed, 6) ) . ' ' . $anti_timeout_counter . TEXT_LPS_FEED_RECORDS . NL;
}

if (isset($upload) && $upload == "yes") {
	echo TEXT_LPS_UPLOAD_STARTED . NL;
	//echo trim(LPS_SERVER) . ' ' .  LPS_USERNAME . ' ' .  LPS_PASSWORD . ' ' . $outfile;
	if($lps->ftp_file_upload(trim(LPS_SERVER), LPS_USERNAME, LPS_PASSWORD, $outfile)) {
		echo TEXT_LPS_UPLOAD_OK . NL;
		$db->execute("update " . TABLE_CONFIGURATION . " set configuration_value = '" . date("Y/m/d H:i:s") . "' where configuration_key='LPS_UPLOADED_DATE'");
	} else {
		echo TEXT_LPS_UPLOAD_FAILED . NL;
	}
}
?>